//
//  ImageDownloaderOperation.m
//  RBIOSBase
//
//  Created by ren on 28/09/2017.
//  Copyright © 2017 bryan. All rights reserved.
//

#import "ImageDownloaderOperation.h"

@interface ImageDownloaderOperation ()<NSURLSessionDataDelegate>

@property (nonatomic, strong) NSURLSession *urlSession;
@property (nonatomic, strong) NSURLSession *ownedSession;
@property (nonatomic, strong) NSURLRequest *urlRequest;
@property (nonatomic, strong) NSURLSessionDataTask *dataTask;
@property (nonatomic, strong) NSMutableData *mutableData;

@end

@implementation ImageDownloaderOperation

- (instancetype)initWithSession:(NSURLSession *)urlSession request:(NSURLRequest *)urlRequest
{
	if (self = [super init]) {
		self.urlSession = urlSession;
		self.urlRequest = urlRequest;
	}
	return self;
}

- (void)start
{
	@synchronized (self) {
		NSURLSession *session = self.urlSession;
		if (!self.urlSession) {
			NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
			sessionConfiguration.timeoutIntervalForRequest = 15.0;
			self.ownedSession = [NSURLSession sessionWithConfiguration:sessionConfiguration
															  delegate:self
														 delegateQueue:nil];
			session = self.ownedSession;
			
		}
		self.dataTask = [session dataTaskWithRequest:self.urlRequest];
	}
	[self.dataTask resume];
}

#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
	completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
	[self.mutableData appendData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error
{
	self.dataTask = nil;
	// 请求完成,成功或者失败的处理
	NSData *data = nil;
	if (self.mutableData) {
		data = [self.mutableData copy];
		self.mutableData = nil;
	}
	if (data) {
		if (self.reciverImage) {
			NSString *keyUrlString = [task.response.URL absoluteString];
			self.reciverImage(data, keyUrlString);
		}
	}
	[session finishTasksAndInvalidate];
	
	if (self.ownedSession) {
		[self.ownedSession invalidateAndCancel];
		self.ownedSession = nil;
	}
}

@end
